<?php

/*
* 案件导入
*/

class PubliccaseimportController extends Controller_Base
{
    public function init()
    {
        parent::init();
    }


    //案件上传批次列表
    public function indexAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $id = trim($request->getQuery('id', ''));
        $mediationOrganId  = intval($request->getQuery('mediationOrganId', 0));
        $status = intval($request->getQuery('status', 0));
        $submitStatus = intval($request->getQuery('submitStatus', 0));
        //检测批次解析和提交
        $this->checkEntryRecord();

        $where = $this->getWhere();
        if($id){
            array_push($where,"id = ".$id);
        }
        if($status){
            array_push($where,"status = ".$status);
        }
        if($mediationOrganId){
            array_push($where,"mediationOrganId = ".$mediationOrganId);
        }
        if($submitStatus){
            array_push($where,"submitStatus = ".$submitStatus);
        }
        $add_begin_end = trim($this->getRequest()->getQuery('add_begin_end', ''));
        if($add_begin_end){
            $query['add_begin_end'] = $add_begin_end;
            $date_tmp =  explode(" 到 ",$add_begin_end);
            $begin_date = $date_tmp[0];
            $end_date = $date_tmp[1];
            if (!empty($begin_date) || !empty($end_date)) {
                $begin_date = $begin_date ? $begin_date . " 00:00:00" : "";
                $end_date = $end_date ? $end_date . " 23:59:59" : "";
            }
            if ($end_date) {
                $end_date = strtotime($end_date);
                array_push($where, "addTime <= {$end_date}");

            }
            if ($begin_date) {
                $begin_date = strtotime($begin_date);
                array_push($where, "addTime >= {$begin_date}");
            }
        }


        $query = [
            'id' => $id,
            'status' => $status,
            'mediationOrganId' => $mediationOrganId,
            'submitStatus' => $submitStatus,
            'add_begin_end' => $add_begin_end,
            'limit' => $limit,
        ];

        $page = $page ? $page : 1;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => ($page - 1) * $limit,
            'order' => 'id DESC'
        );

        $arrList = Module_Mediate_PublicEntryImport::getInstance()->getAllBySearch([],$seacher,true);
        $total = Module_Mediate_PublicEntryImport::getInstance()->getAllBySearch(["count(*) as num"], ['where' => $where], true);
        $total = $total[0]['num'];
        $totalPage = ceil($total / $limit);
        //赋值调解部门
        $this ->getMediationOrgan();

        SmartyAdapter::assign('arrList', $arrList);
        SmartyAdapter::assign('disputeType',  Module_Mediate_Case::$disputeType);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('page_query', http_build_query($query));
    }

    //导入案件
    public function uploadAction()
    {
        if ($this->getRequest()->getPost()) {
            $data = $this->getRequest()->getPost('data', '');
            parse_str(urldecode($data),$data);
            if(empty($data['disputeType'])){
                AjaxTool::returnJsonData(403,'请选择纠纷类型');
            }
            $file = $this->getRequest()->getFiles('file');
            if ($file['error'] == 4) {
                AjaxTool::returnJsonData(404,'请上传文件');
            }
            $img_url = '';
            if ($file['error'] != 4) {
                $uploadFile = Lib_Upload::getInstance()->uploadFile($file, 'caseupload');
                if (!$uploadFile || $uploadFile['code']) {
                    AjaxTool::returnJsonData(405,'上传失败');
                }
                $img_url = $uploadFile['data'];
            }
            //$img_url = '/2023-04-25.xlsx';
            $file_path=  '/resource' . $img_url;
            $url = realpath(LIBRARY_DIR . '/../') . '/resource' . $img_url;
            $file_info = pathinfo($url);
            if ($file_info && strtolower($file_info['extension']) == 'csv') {
                $res = array_map('str_getcsv', file($url));
                if ($res) {
                    unset($res[0]);
                }
            } else {
                try {
                    $res = Lib_XlsxRead::getInstance()->execute($url,1);
                } catch (Exception $e) {
                    AjaxTool::returnJsonData(406,'文件格式不对'.$e);
                }
                if (empty($res)) {
                    AjaxTool::returnJsonData(407,'未发现数据');
                }
            }
            $header = $res[1];
            unset($res[1]);
            if (!$res) {
                AjaxTool::returnJsonData(408, "未发现数据");
            }
            if(empty($header)){
                 AjaxTool::returnJsonData(409, "未发现表格表头");
            }
            //先生成批次,然后再进行检查
            $entry_record_insert = [
                'mediationOrganId'=> $this->admin['mediationOrganId'] ?? '',
                'mediationOrganIdName'=> $this->admin['mediationOrganIdName'] ?? '',
                'uploadUid'=> $this->admin['id'],
                'uploadName'=> $this->admin['name'],
                'status'=>1,//状态 0：未解析 1：解析中；2：解析完成；；3：解析失败
                'submitStatus'=>1,//1未提交 2提交
                'addTime'=>time(),
                'updateTime'=>time(),
                'disputeType'=>$data['disputeType'],
                'desc'=>'',
                'uploadUid' => $this->admin['id'],
                'uploadName' => $this->admin['name'],
                'filePath'=>$file_path,//上传文件地址
            ];

            $recordId = Module_Mediate_PublicEntryImport::getInstance()->singleInsert($entry_record_insert);
            if(!$recordId){
                AjaxTool::returnJsonData(500, "入库失败");
            }
            $this->checkCase($res,$header,$recordId,$data['disputeType']);

        }
        AjaxTool::returnJsonData(500, "未检测到上传数据");

    }

    //检测案件
    public function checkCase($upload_case,$header,$record_id,$disputeType){
        $success = 0;
        $fail = 0;
        $fields = Lib_Var::$excel_title['publicCase'];
        foreach ($header as $key => $field){
            $header[$key] = preg_replace('/\(.*?\)|\（.*?\）/', '', $field);
        }
        $tidy_case = [];
        foreach ($upload_case as $key => $case){
            foreach ($fields as $k => $field){
                $tidy_case[$key][$k] = trim($case[$field['site']]);
            }
        }
        foreach ($tidy_case as $k=>$case) {
            $insert=[
                'mediationNum'=>empty($case['mediationNum']) ? '' : $case['mediationNum'],
                'mediationOrganId'=> $this->admin['mediationOrganId'] ?? '',//调解部门id
                'litigantName'=>$case['litigantName'],
                'assetsName'=>$case['assetsName'],
                'cardId'=>$case['cardId'],
                'debtTarget'=>$case['debtTarget'],
                'debtPrincipal'=>$case['debtPrincipal'],
                'disputeType'=>$disputeType,
                'caseStatus'=>0,
                'importRecordId'=>$record_id,
                'addTime'=>time(),
                'updateTime'=>time(),
            ];
            $check_res = Lib_Var::checkData($fields,$case);
            if($check_res['error'] == 1){
                $insert['caseStatus'] = 3;
                $insert['desc'] .= $check_res['error_desc'];
            }

            $post_data = array(
                'type' => 'Module_Task_Case',
                'method' => 'addPublicCase',
                'data' => $insert
            );
            @Module_Queue_Base::addQueue($post_data,'',1);
            if($insert['caseStatus'] == 0){
                $success++;
            }elseif($insert['caseStatus'] == 3){
                $fail++;
            }

        }
        //更新批次解析成功和失败数
        $record_updata = [
            'id' => $record_id,
            'sucessNum' => $success,
            'errorNum' => $fail,
        ];
        Module_Mediate_PublicEntryImport::getInstance()->singleUpdate($record_updata);
        AjaxTool::returnJsonData(200,"案件批量异步解析中，稍后导入记录中查看解析结果");
    }

    //下载文件模板
    public function downTemplateAction()
    {
        $paramList = [
            [
                1 => '张三',
                2 => '440100199005251234',
                3 => '平安银行广州支行',
                4 => '1000.10',
                5 => '1100.10',
                6 => '金融调解509号',

            ],
            [
                1 => '李四',
                2 => '123456',
                3 => '平安银行广州支行',
                4 => '1000.10',
                5 => '1200.10',
                6 => '金融调解510号',
            ],
            [
                1 => '王五',
                2 => '12345X',
                3 => '平安银行广州支行',
                4 => '1000.10',
                5 => '1300.10',
                6 => '',
            ],
        ];
        $header=array_values(array_column(Lib_Var::$excel_title['publicCase'],'name'));
        Lib_XlsxExport::getInstance()->downExcel($paramList, $header,'公示案件导入模板');
        exit;
    }
    //案件上传批次列表
    public function recordDetailAction()
    {
        $request = $this->getRequest();
        $page = intval($request->getQuery('page', 1));
        $limit = intval($request->getQuery('limit', 10));
        $recordId = intval($request->getQuery('recordId', 0));
        $status = intval($request->getQuery('status', 0));

        $query = [
            'status' => $status,
            'limit' => $limit,
            'recordId' => $recordId,
        ];
        $where= $this->getWhere();
        if($recordId){
            array_push($where,"importRecordId = {$recordId}");
        }
        if($status){

            if($status == 9){
                array_push($where,"caseStatus = 0");
            }else{
                array_push($where,"caseStatus = ".$status);

            }
        }

        $page = $page ? $page : 1;
        $start = ($page - 1) * $limit;
        $seacher = array(
            'where' => $where,
            'limit' => $limit,
            'start' => $start,
            'order' => 'id DESC'
        );
        $arrList = Module_Mediate_PublicCase::getInstance()->getAllBySearch([],$seacher,true);
        $total = Module_Mediate_PublicCase::getInstance()->getAllBySearch(["count(*) as total"],['where' => $where],true);
        $total = $total[0]['total'];
        $totalPage = ceil($total / $limit);
        SmartyAdapter::assign('arrList', $arrList);
        SmartyAdapter::assign('totalPage', $totalPage);
        SmartyAdapter::assign('totalnum', $total);
        SmartyAdapter::assign('pagesize', $limit);
        SmartyAdapter::assign('curPageNum', $page);
        SmartyAdapter::assign('query', $query);
        SmartyAdapter::assign('page_query', http_build_query($query));

    }

    //删除批次
    public function delentryrecordAction()
    {
        $request = $this->getRequest();
        $recordId = $request->getPost('recordId', 0);
        if (empty($recordId)) {
            AjaxTool::returnJsonData(400, "缺少参数");
        }
        //判断是否被提交了,提交了 就不能删除
        $entryRecord = Module_Mediate_PublicEntryImport::getInstance()->getItemById($recordId);
        if (empty($entryRecord)) {
            AjaxTool::returnJsonData(400, "批次不存在");
        }

        if ($entryRecord['submitStatus'] != 1) {
            AjaxTool::returnJsonData(400, "已提交处理的不能删除");
        }

        Module_Mediate_PublicEntryImport::getInstance()->beginTransaction();
        $res = Module_Mediate_PublicEntryImport::getInstance()->deleteItemById($recordId);
        if (!$res) {
            Module_Mediate_PublicEntryImport::getInstance()->rollback();
            AjaxTool::returnJsonData(400, "删除失败");
        }
        $res = Module_Mediate_PublicCase::getInstance()->deleteItemById($recordId, 'recordId');
        if (!$res && $res !== 0) {
            Module_Mediate_PublicEntryImport::getInstance()->rollback();
            AjaxTool::returnJsonData(400, "详情记录删除失败");
        }
        Module_Mediate_PublicEntryImport::getInstance()->commit();
        AjaxTool::returnJsonData(200, "操作成功");
    }

    //提交批次
    public function caseSubmitAction(){
        $time = time();
        $recordId = $this->getRequest()->getPost('recordId', '');
        if(empty($recordId)){
            AjaxTool::returnJsonData(400, "参数异常");
        }
        //案件批次提交
        $record = Module_Mediate_PublicEntryImport::getInstance()->getOne(['id','status'],['submitStatus=1',"id = {$recordId}"]);
        if($record['status'] == 1){
            AjaxTool::returnJsonData(200, '正在解析中，请解析完成后再提交');
        }

        //更新批次为提交中
        $res = Module_Mediate_PublicEntryImport::getInstance()->singleUpdate(
            [
            "id"=>$recordId,
            "updateTime" => $time,
            "submitStatus"=>2
            ]
        );
        if(!$res){
            AjaxTool::returnJsonData(400, '导入失败，批次数据库跟新异常');
        }
        $res = Module_Mediate_PublicCase::getInstance()->updateStatusByImportId($recordId,4,0);
        if(!$res){
            AjaxTool::returnJsonData(400, '导入失败，数据库跟新异常');
        }
        //修改案件号
        $mediationNum = SmartyAdapter::getTplVars('mediationNum');
        @Module_Mediate_PublicCase::getInstance()->updateNumByImportId($recordId,$mediationNum);
        AjaxTool::returnJsonData(200, '提交成功'.$res.'条');
    }

    private function tidyData($data){
        $tidyData = [];
        $fields = Lib_Var::$excel_title['caseDetail'];
        foreach ($fields as $key => $val){
            $tidyData[preg_replace('/\(.*?\)|\（.*?\）/', '', $val['name'])] = $data[$key];
        }
        if(!empty($data['debtor'])){
            $debtorfields = Lib_Var::$excel_title['debtor'];

            foreach ($data['debtor'] as $k => $debtor){
                foreach ($debtorfields as $key => $val){
                    $tidyData["公债人{$k}".preg_replace('/\(.*?\)|\（.*?\）/', '', $val['name'])] = $debtor[$key];
                }
            }
        }
        if(!empty($data['attachInfo'])){
           foreach ($data['attachInfo'] as  $attachInfo){
               $tidyData[$attachInfo['key']] = $attachInfo['val'];
           }
        }
        return $tidyData;
    }
    protected function checkEntryRecord(){
        $record_where = [
            'status =1',
        ];
        $records = Module_Mediate_PublicEntryImport::getInstance()->getAllBySearch(['id','status','sucessNum','errorNum'],['where'=>$record_where]);
        if(!empty($records)){
            foreach($records as $k=>$record){
                $up = [];

                //解析完成
                if($record['status'] == 1){
                    $analysis_where = [
                        'caseStatus in (0,3)',
                        'importRecordId='.$record['id'],
                    ];
                    $analysis_nofinish = Module_Mediate_PublicCase::getInstance()->getAllBySearch(['count(*) as total'],['where'=>$analysis_where],false);
                    if($analysis_nofinish['0']['total'] >= ($record['sucessNum']+$record['errorNum'])){
                        $up['status'] = 2;
                    }
                }

                if(!empty($up)){
                    $up['id'] = $record['id'];
                    Module_Mediate_PublicEntryImport::getInstance()->singleUpdate($up);
                }
            }
        }
    }

    public function isshowAction(){
        $recordId = $this->getRequest()->getPost('id', 0);
        $showtype = $this->getRequest()->getPost('showtype', 0);
        $record = Module_Mediate_PublicEntryImport::getInstance()->getItemById($recordId);
        if(empty($record)){
            AjaxTool::returnJsonData(400, '找不到相应记录');
        }
//        $auditcase = Module_Mediate_PublicCase::getInstance()->getOne(['id'],['caseStatus in (0,4)']);
//
//        if($auditcase){
//            AjaxTool::returnJsonData(400, '还有未审核案件或未确定导入');
//        }
        Module_Mediate_PublicEntryImport::getInstance()->singleUpdate([
            'id' => $recordId,
            'isShow' => $showtype,
        ]);
        $status =  $showtype == 0 ? 2 : 1;
        $whereStatus = $status == 1 ? 2 : 1;
        $res = Module_Mediate_PublicCase::getInstance()->updateStatusByImportId($recordId,$status,$whereStatus);
        if(!$res){
            AjaxTool::returnJsonData(400, '数据库跟新异常');
        }
        $type = $showtype == 1 ?'开启':"关闭";
        if($res){
            AjaxTool::returnJsonData(200, "{$type}成功");

        }
        AjaxTool::returnJsonData(400, "{$type}失败");


    }
}
